﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Drawing;
using System.Reflection;
using System.Diagnostics;

namespace KeyboardRemapper
{
   public class StatusIcon : Form
   {
      /// <summary>
      /// The main entry point for the application.
      /// </summary>
      [STAThread]
      static void Main()
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new StatusIcon());
      }

      static NotifyIcon m_icon;
      private ContextMenuStrip contextMenuStrip1;
      public StatusIcon()
      {
         m_icon = new NotifyIcon();
         m_icon.Icon = new Icon(typeof(StatusIcon), "MainIcon.ico");
         contextMenuStrip1 = new ContextMenuStrip();
         contextMenuStrip1.Items.Add("Edit keys", null, EditKeysClicked);
         contextMenuStrip1.Items.Add(new ToolStripSeparator());
         contextMenuStrip1.Items.Add("Exit", null, ExitClicked);
         m_icon.Visible = true;
         ShowInTaskbar = false;
         Visible = false;
         WindowState = FormWindowState.Minimized;
         m_icon.ContextMenuStrip = contextMenuStrip1;
         if (!File.Exists("macros.txt"))
         {
            using (Stream stream = Assembly.GetExecutingAssembly()
                         .GetManifestResourceStream("KeyboardRemapper.macros.txt"))
            using (StreamReader reader = new StreamReader(stream))
            {
               File.WriteAllText("macros.txt", reader.ReadToEnd());
            }
         }

         KeyInterceptor.Start();

      }

      protected override void SetVisibleCore(bool value)
      {
         base.SetVisibleCore(false);
      }

      void EditKeysClicked(object sender, EventArgs e)
      {
         frmEditMacroList f = new frmEditMacroList();
         f.ShowDialog();
      }

      void ExitClicked(object sender, EventArgs e)
      {
         Exit();
      }

      public static void Exit()
      {
         KeyInterceptor.End();
         m_icon.Visible = false;
         LibBase.ThreadPool.EndThreads();
         Application.Exit();
      }

   }
}
